package com.mycat.web.content;

import com.mycat.common.entity.InvokeResult;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * @author roger.
 * @email luojie@yzworld.cn
 * @date 2016/10/21
 */
public class CustomExceptionHandler implements HandlerExceptionResolver{
    private static Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception exception) {
        ModelAndView view = new ModelAndView(new JsonView());
        InvokeResult invokeResult =null;
        try {
            if(exception instanceof UnauthorizedException){
                invokeResult = InvokeResult.failure(401, "您没有权限，请勿非法操作！");
            }else if(exception instanceof UnauthenticatedException){
                invokeResult = InvokeResult.failure(401, "您授权异常，请勿非法操作！");
            }else if(exception instanceof IOException){
                invokeResult = InvokeResult.error();
            }else if(exception instanceof UnknownSessionException){
                invokeResult = InvokeResult.error();
            } else if(exception instanceof Exception){
                invokeResult = InvokeResult.error();
            }
            logger.error(exception.getMessage(),exception);
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(),e);
        }
        view.addObject("code",invokeResult.getCode());
        view.addObject("msg", invokeResult.getMsg());
        return view;
    }
}
